import {Router} from '@angular/router';
import {Component} from '@angular/core';
import {FormGroup, FormBuilder, Validators} from '@angular/forms';
import {SettingsService} from '@core/services/settings.service';
import {_HttpClient} from "@core/services/http.client";
import {HttpHeaders} from "@angular/common/http";
import {TokenService} from "@core/net/token/token.service";
import {NzMessageService} from "ng-zorro-antd";
import * as moment from 'moment';
import {TokenData} from "@core/net/token/token.type";
import {HttpService} from "@core/services/http.service";
import {ServerSocket} from "@core/services/ws.service";

@Component({
    selector: 'app-pages-login',
    templateUrl: './login.component.html'
})
export class LoginComponent {
    valForm: FormGroup;

    constructor(public ws: ServerSocket,public settings: SettingsService, private http: HttpService, private token: TokenService, fb: FormBuilder, private router: Router, private msgService: NzMessageService) {
        this.valForm = fb.group({
            email: [null, Validators.compose([Validators.required])],
            password: [null, Validators.required],
            remember_me: [null]
        });
    }

    public static HTTP_IP_PORT = "http://192.168.0.104:8080";

    submit() {
        // tslint:disable-next-line:forin
        for (const i in this.valForm.controls) {
            this.valForm.controls[i].markAsDirty();
        }
        if (this.valForm.valid) {
            var param = {LoginName: this.valForm.value.email, LoginPwd: this.valForm.value.password}

            this.http.login(param).subscribe(res => {
                if (res['code'] == '0') {
                    this.msgService.success(res['msg'])
                    let tokenData = <TokenData>{
                        access_token: res['accesstoken'],
                        expire_time: moment().add(7, 'days').unix(),
                        refresh_token: res['accesstoken'],
                        refresh_token_valid_time: moment().add(14, 'days').unix(),
                        role:res['role'],
                        user_name: res['username'],
                        user_id:res['userId'],
                        sch_id:res['sch_id']
                    };
                    this.token.data = tokenData;

                    this.ws.reconnect()
                    this.router.navigate(['index']);
                } else {
                    this.msgService.error(res['msg'])
                }
            })


        }
    }
}
